<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace app\common\model;

use app\common\cachemodel\ZlUserNoComment;
use app\common\lib\exception\ApiException;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Log as Log;

class User extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user';

    const CACHE_KEY = 'userinfo:';// . $uid
    const CACHE_TIME = 86400;

    /**
     * 获取用户信息
     * @param array $map
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws ApiException
     */
    public function getUserinfo($map = [])
    {
        $userinfo = false;

        if ($this->cache_on >= 1 && isset($map['id']))
        {
            $userinfo = Cache::get(self::CACHE_KEY . $map['id']);
        }
        if (!$userinfo || empty($userinfo) || (isset($map['token']) && $userinfo['token'] != $map['token']) || !isset($userinfo['reg_time']))
        {
            try
            {
                if (isset($map['token'])) unset($map['id']);

                $field = 'id,uen,token,token_expire,tel,uc_id,nickname,sex,avatar,status,has_self_recode,forbidden,regid,young_pwd,is_login_record,temporary_tel,tel_bind_time,reg_time';

                $userinfo = $this->field($field)->where($map)->findOrFail();

                $userinfo = json_decode(json_encode($userinfo, true), true);

                $recordInfo = (new \app\common\cachemodel\Recode())->getRecodeLists($userinfo['id'], 1);

                if ($recordInfo)
                {
                    $userinfo['rid'] = (int)($recordInfo['id'] ?? 0);
                    $userinfo['nickname'] = $recordInfo['name'] ?? '';
                    $userinfo['avatar'] = $recordInfo['avatar'] ?? '';
                } else
                {
                    $userinfo['rid'] = 0;
                }
                // 用户是否禁止评论
                $userinfo['no_comment'] = (new ZlUserNoComment())->getUserIsNoComment((int)$userinfo['id']);

                Cache::set(self::CACHE_KEY . $userinfo['id'], $userinfo, self::CACHE_TIME);

            }
            catch (DataNotFoundException $e)
            {
//                Log::write("获取用户查询失败:{$e->getMessage()};sql==>：{$this->getLastSql()}", 'error', true);
                throw new ApiException('当前账号登录过期，请您重新登录。', 200, 403);
            }
            catch (ModelNotFoundException $e)
            {
//                Log::write("获取用户查询失败:{$e->getMessage()};sql==>：{$this->getLastSql()}", 'error', true);
                throw new ApiException('当前账号登录过期，请您重新登录。', 200, 403);
            }
            catch (\Exception $e)
            {
                Log::write('获取用户信息失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error', true);
                throw new ApiException('当前账号登录过期，请您重新登录。', 200, 403);
            }
        }

        if (!isset($userinfo['temporary_tel'], $userinfo['tel_bind_time']) || !$userinfo['temporary_tel'] || (time() - $userinfo['tel_bind_time'] > 86400 * 30 * 6))
        {
            $userinfo['temporary_tel'] = '';
            $userinfo['tel_bind_time'] = 0;
        }

        $userinfo['young_pwd'] = $userinfo['young_pwd'] ?? '';

        $userinfo['young_model'] = $userinfo['young_pwd'] ? true : false;
        $userinfo['id'] = (int)$userinfo['id'];
        $userinfo['nickname'] = $userinfo['nickname'] ?? '';
        $userinfo['avatar'] = $userinfo['avatar'] ?? '';
        return $userinfo;
    }

    /**
     * 更新用户信息
     * @param array $map
     * @param array $data
     * @throws ApiException
     */
    public function updateUserinfo($map = [], $data = [])
    {
        if (!empty($map) && !empty($data))
        {
            try
            {
                $this->where($map)->update($data);

                Cache::rm(self::CACHE_KEY . $map['id']);
            }
            catch (\Exception $e)
            {
                throw new ApiException('当前账号登录过期，请您重新登录。', 200, 403);
            }
        }
    }

    /**
     * @param array $map
     * @throws ApiException
     */
    public function updateRegid($map = [])
    {
        if ($map['uid'] && $map['regid'])
        {
            $userinfo = $this->getUserinfo(['id' => $map['uid']]);
            // 有变化  进行更新
            if ($userinfo['regid'] != $map['regid'])
            {
                $userinfo['regid'] = $map['regid'];
                try
                {
                    $this->where(['id' => $map['uid']])->update(['regid' => $map['regid']]);

                    Cache::set(self::CACHE_KEY . $userinfo['id'], $userinfo, 86400 * 3);
                }
                catch (\Exception $e)
                {
                    throw new ApiException('当前账号登录过期，请您重新登录。', 200, 403);
                }
            }
        }
        return;
    }

    /**
     * 判断用户是否绑定准了号
     * @param array $userinfo
     * @return false|string
     * @throws ApiException
     */
    public function check_uen($userinfo = [])
    {
        // 添加准了号
        if ($userinfo && (!isset($userinfo['uen']) || !$userinfo['uen'] || empty($userinfo['uen'])))
        {
            $uuid = substr(md5(microtime() . $userinfo['id']), 0, 12);

            $uen = ['uen' => $uuid];

            try
            {
                $this->save($uen, ['id' => $userinfo['id']]);

                Cache::rm(self::CACHE_KEY . $userinfo['id']);

                return $uuid;
            }
            catch (\Exception $e)
            {
                Log::write('准了号绑定失败：uid=' . $userinfo['id'], 'error');
//                throw new ApiException('准了号绑定失败');
            }
        }
        return false;
    }

    /**
     * 批量获取用户信息
     * @param array $uids
     * @param array $filed 预备参数
     * @return array
     * @throws ApiException
     */
    public function batchGetUserInfo(array $uids, $filed = [])
    {
        $userInfoList = [];
        foreach ($uids as $uid)
        {
            try
            {
                $userInfoList[$uid] = $this->getUserinfo(['id' => $uid]);
            }
            catch (\Exception $e)
            {
                $userInfoList[$uid] = null;
            }
        }

        return $userInfoList;
    }

    /**
     * 删除用户缓存
     * @param $uid
     */
    public function removeUserCache($uid)
    {
        Cache::rm(self::CACHE_KEY . $uid);
    }
}
